package com.dragee.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragee.common.PageUtils;
import com.dragee.common.R;
import com.dragee.common.VerifyParam;
import com.dragee.config.exception.AuthException;
import com.dragee.config.exception.BusinessException;
import com.dragee.constants.AuthConstants;
import com.dragee.modules.sys.dao.SysUserRoleMapper;
import com.dragee.modules.sys.entity.SysRole;
import com.dragee.modules.sys.entity.SysUserRole;
import com.dragee.modules.sys.entity.UserEntity;
import com.dragee.modules.sys.service.ISysRoleService;
import com.dragee.modules.sys.service.UserRoleService;
import com.dragee.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;

/**
 * @author tys on 2023/4/13
 */
@RestController
@RequestMapping("work/adminSheng")
@Api(tags = "Modules - 省赛管理员管理")
public class AdminShengController {
    @Autowired
    private UserService userService;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 列表
     */
    @GetMapping("list")
    @ApiOperation("用户列表")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params, "admin_s");
        return R.ok().put("data", page);
    }

    /**
     * 信息
     */
    @GetMapping("{userid}")
    @ApiOperation("用户信息")
    public R info(@PathVariable("userid") Long userid){
        UserEntity user = userService.getById(userid);
        return R.ok().put("data", user);
    }

    /**
     * 保存
     */
    @PostMapping("saveOrUpdate")
    @ApiOperation("保存或修改用户")
    public R saveOrUpdate(@RequestBody UserEntity user){
        VerifyParam.notNull(user);
        String password = new Sha256Hash(user.getPassword(), AuthConstants.SLAT_PWD).toHex();
        if (user.getUserId() == null) {
            // 新增
            //用户名唯一性校验
            int count = userService.count(new QueryWrapper<UserEntity>().eq("username", user.getUsername()));
            if (count!=0){
                throw new BusinessException(502,"用户名已存在");
            }
            user.setPassword(password);
            userService.save(user);

            /*增加角色*/
            SysRole role = sysRoleService.getRoleByKey("admin_s");
            if (role == null) {
                throw new AuthException(801, "角色不存在");
            }
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getUserId());
            userRole.setRoleId(role.getRoleId());
            sysUserRoleMapper.insert(userRole);
        } else {
            // 修改
            int count = userService.count(new QueryWrapper<UserEntity>()
                    .ne("userId", user.getUserId())
                    .eq("username", user.getUsername()));
            if (count!=0) {
                throw new BusinessException(502,"用户名已存在");
            }
            userService.saveOrUpdate(user);
        }
        return R.ok();
    }


    @GetMapping("delete-by-ids")
    @ApiOperation("批量删除")
    public R deletes(String userIds){
        String[] idArr = userIds.split(",");
        Arrays.stream(idArr).forEach(id -> userService.removeById(Long.parseLong(id)));
        return R.ok();
    }

    @GetMapping("delete-by-id")
    @ApiOperation("删除用户通过UserId")
    public R deleteById(String userId){
        int count = userService.count(new QueryWrapper<UserEntity>().eq("parentId", userId));
        if (count > 0) {
            throw new BusinessException(501, "当前用户存在下级用户, 不可删除");
        }
        userService.removeById(Long.parseLong(userId));
        return R.ok();
    }

    /**
     * 删除
     */
    @GetMapping("change-status")
    @ApiOperation("切换状态")
    public R changeStatus(String status, String userId){
        UserEntity user = userService.getById(Long.parseLong(userId));
        user.setStatus(status);
        userService.saveOrUpdate(user);
        return R.ok();
    }





}
